/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */

package com.iwindplus.mgt.server.service.system.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.github.yulichang.repository.JoinCrudRepository;
import com.iwindplus.boot.domain.constant.CommonConstant;
import com.iwindplus.boot.domain.dto.MessageDTO;
import com.iwindplus.boot.domain.enums.BizCodeEnum;
import com.iwindplus.boot.domain.enums.EnableStatusEnum;
import com.iwindplus.boot.domain.enums.OperateTypeEnum;
import com.iwindplus.boot.domain.exception.BizException;
import com.iwindplus.mgt.domain.constant.MgtConstant;
import com.iwindplus.mgt.domain.dto.system.ServerDTO;
import com.iwindplus.mgt.domain.dto.system.ServerRouteParamDTO;
import com.iwindplus.mgt.domain.dto.system.ServerSearchDTO;
import com.iwindplus.mgt.domain.enums.MgtCodeEnum;
import com.iwindplus.mgt.domain.vo.system.ServerBaseVO;
import com.iwindplus.mgt.domain.vo.system.ServerPageVO;
import com.iwindplus.mgt.domain.vo.system.ServerRouteDefinitionVO;
import com.iwindplus.mgt.domain.vo.system.ServerVO;
import com.iwindplus.mgt.server.mapper.system.ServerMapper;
import com.iwindplus.mgt.server.model.system.ServerDO;
import com.iwindplus.mgt.server.service.system.ServerService;
import jakarta.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 服务业务层接口实现类.
 *
 * @author zengdegui
 * @since 2020/3/25
 */
@Slf4j
@Service
@CacheConfig(cacheNames = {"server"})
@Transactional(rollbackFor = Exception.class)
public class ServerServiceImpl extends JoinCrudRepository<ServerMapper, ServerDO> implements ServerService {

    @Resource
    private RedissonClient redissonClient;

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"server"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true)
        }
    )
    @Override
    public boolean save(ServerDTO entity) {
        entity.setStatus(EnableStatusEnum.ENABLE);
        entity.setHideFlag(Boolean.FALSE);
        this.getNameIsExist(entity.getName().trim());
        // 校验路由ID是否存在
        this.getRouteIdIsExist(entity.getRouteId().trim());
        // 判断路由断言中路由地址是否重复配置
        this.getPredicatesIsExist(entity.getPredicates());
        entity.setSeq(this.getNextSeq());
        entity.setBuildInFlag(Boolean.FALSE);
        ServerDO model = BeanUtil.copyProperties(entity, ServerDO.class);
        boolean data = super.save(model);
        if (data) {
            entity.setId(model.getId());
            this.sendMsg(OperateTypeEnum.ADD);
        }
        return data;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"server"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true)
        }
    )
    @Override
    public boolean saveOrEditBatch(List<ServerDTO> entities) {
        if (CollUtil.isEmpty(entities)) {
            return Boolean.FALSE;
        }
        List<Boolean> resultList = new ArrayList<>(10);
        entities.forEach(entity -> {
            final ServerDO data = super.getOne(Wrappers.lambdaQuery(ServerDO.class)
                .eq(ServerDO::getRouteId, entity.getRouteId())
                .select(ServerDO::getId, ServerDO::getVersion));
            if (Objects.isNull(data)) {
                if (Boolean.FALSE.equals(this.checkPredicates(entity.getPredicates()))) {
                    entity.setSeq(this.getNextSeq());
                    ServerDO model = BeanUtil.copyProperties(entity, ServerDO.class);
                    resultList.add(super.save(model));
                }
            } else {
                ServerDO model = BeanUtil.copyProperties(entity, ServerDO.class);
                model.setId(data.getId());
                model.setVersion(data.getVersion());
                resultList.add(super.updateById(model));
            }
        });
        if (resultList.stream().allMatch(Boolean.TRUE::equals)) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"server"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true)
        }
    )
    @Override
    public boolean removeByIds(List<Long> ids) {
        List<ServerDO> list = super.listByIds(ids);
        if (CollUtil.isEmpty(list)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        boolean match = list.stream().anyMatch(ServerDO::getBuildInFlag);
        if (Boolean.TRUE.equals(match)) {
            throw new BizException(BizCodeEnum.HAS_BUILD_IN_DATA);
        }
        final boolean result = super.removeByIds(ids);
        if (result) {
            this.sendMsg(OperateTypeEnum.DELETE);
        }
        return result;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"server"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true)
        }
    )
    @Override
    public boolean edit(ServerDTO entity) {
        ServerDO data = super.getById(entity.getId());
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        if (Boolean.TRUE.equals(data.getBuildInFlag())) {
            throw new BizException(BizCodeEnum.BUILD_IN_DATA_NOT_OPERATE);
        }
        if (CharSequenceUtil.isNotBlank(entity.getName()) && !CharSequenceUtil.equals(data.getName(), entity.getName().trim())) {
            this.getNameIsExist(entity.getName().trim());
        }
        if (CharSequenceUtil.isNotBlank(entity.getRouteId()) && !CharSequenceUtil.equals(data.getRouteId(), entity.getRouteId().trim())) {
            this.getRouteIdIsExist(entity.getRouteId().trim());
        }
        List<ServerRouteParamDTO> dtoList = BeanUtil.copyToList(data.getPredicates(), ServerRouteParamDTO.class);
        if (CollUtil.isNotEmpty(entity.getPredicates())
            && !CharSequenceUtil.equals(this.getPattern(dtoList), this.getPattern(entity.getPredicates()))) {
            this.getPredicatesIsExist(entity.getPredicates());
        }
        if (Objects.isNull(entity.getVersion())) {
            entity.setVersion(data.getVersion());
        }
        ServerDO model = BeanUtil.copyProperties(entity, ServerDO.class);
        boolean result = super.updateById(model);
        if (result) {
            this.sendMsg(OperateTypeEnum.MODIFY);
        }
        return result;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"server"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true)
        }
    )
    @Override
    public boolean editStatus(Long id, EnableStatusEnum status) {
        ServerDO data = super.getById(id);
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        if (Boolean.TRUE.equals(data.getBuildInFlag())) {
            throw new BizException(BizCodeEnum.BUILD_IN_DATA_NOT_OPERATE);
        }
        if (status.equals(data.getStatus())) {
            throw new BizException(BizCodeEnum.ALREADY_OPERATED);
        }
        ServerDO entity = new ServerDO();
        entity.setId(id);
        entity.setStatus(status);
        entity.setVersion(data.getVersion());
        boolean result = super.updateById(entity);
        if (result) {
            this.sendMsg(OperateTypeEnum.MODIFY);
        }
        return result;
    }

    @Caching(
        evict = {
            @CacheEvict(cacheNames = {"server"}, allEntries = true),
            @CacheEvict(cacheNames = {"resource"}, allEntries = true)
        }
    )
    @Override
    public boolean editBuildIn(Long id, Boolean buildInFlag) {
        ServerDO data = super.getById(id);
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        if (buildInFlag.equals(data.getBuildInFlag())) {
            throw new BizException(BizCodeEnum.ALREADY_OPERATED);
        }
        ServerDO param = new ServerDO();
        param.setId(id);
        param.setBuildInFlag(buildInFlag);
        param.setVersion(data.getVersion());
        super.updateById(param);
        return Boolean.TRUE;
    }

    @Override
    public IPage<ServerPageVO> page(ServerSearchDTO entity) {
        PageDTO<ServerDO> page = new PageDTO<>(entity.getCurrent(), entity.getSize());
        page.setOptimizeCountSql(Boolean.FALSE);
        page.setOptimizeJoinOfCountSql(Boolean.FALSE);
        LambdaQueryWrapper<ServerDO> queryWrapper = Wrappers.lambdaQuery(ServerDO.class)
            .orderByDesc(ServerDO::getModifiedTime);
        if (Objects.nonNull(entity.getStatus())) {
            queryWrapper.eq(ServerDO::getStatus, entity.getStatus());
        }
        if (CharSequenceUtil.isNotBlank(entity.getName())) {
            queryWrapper.eq(ServerDO::getName, entity.getName().trim());
        }
        if (CharSequenceUtil.isNotBlank(entity.getRouteId())) {
            queryWrapper.eq(ServerDO::getRouteId, entity.getRouteId().trim());
        }
        queryWrapper.select(ServerDO::getId, ServerDO::getCreatedTime, ServerDO::getCreatedBy, ServerDO::getModifiedTime, ServerDO::getModifiedBy,
            ServerDO::getVersion, ServerDO::getStatus, ServerDO::getName, ServerDO::getRouteId, ServerDO::getUri, ServerDO::getHideFlag,
            ServerDO::getBuildInFlag);
        final PageDTO<ServerDO> modelPage = super.page(page, queryWrapper);
        return modelPage.convert(model -> BeanUtil.copyProperties(model, ServerPageVO.class));
    }

    @Cacheable(key = "#root.methodName", unless = "#result == null")
    @Override
    public List<ServerRouteDefinitionVO> listRouteDefinition() {
        LambdaQueryWrapper<ServerDO> queryWrapper = Wrappers.lambdaQuery(ServerDO.class)
            .eq(ServerDO::getStatus, EnableStatusEnum.ENABLE)
            .orderByAsc(List.of(ServerDO::getSeq, ServerDO::getRouteId));
        List<ServerDO> list = super.list(queryWrapper);
        if (CollUtil.isEmpty(list)) {
            return null;
        }
        final List<ServerRouteDefinitionVO> data = new ArrayList<>(10);
        list.stream().forEach(item -> {
            final ServerRouteDefinitionVO build = ServerRouteDefinitionVO.builder()
                .enabled(item.getStatus().getValue() > 0)
                .id(item.getRouteId())
                .uri(item.getUri())
                .predicates(item.getPredicates())
                .filters(item.getFilters())
                .metadata(item.getMetadata())
                .order(item.getSeq())
                .build();
            data.add(build);
        });
        return data;
    }

    @Cacheable(key = "#root.methodName", unless = "#result == null")
    @Override
    public List<ServerBaseVO> listEnabled() {
        LambdaQueryWrapper<ServerDO> queryWrapper = Wrappers.lambdaQuery(ServerDO.class)
            .eq(ServerDO::getStatus, EnableStatusEnum.ENABLE)
            .eq(ServerDO::getHideFlag, Boolean.FALSE)
            .select(ServerDO::getId, ServerDO::getRouteId, ServerDO::getName)
            .orderByAsc(List.of(ServerDO::getRouteId));
        List<ServerDO> list = super.list(queryWrapper);
        if (CollUtil.isEmpty(list)) {
            return null;
        }
        return BeanUtil.copyToList(list, ServerBaseVO.class);
    }

    @Cacheable(key = "#root.methodName + '_' + #p0", condition = "#p0 != null", unless = "#result == null")
    @Override
    public ServerVO getDetail(Long id) {
        ServerDO data = super.getById(id);
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        return BeanUtil.copyProperties(data, ServerVO.class);
    }

    @Override
    public String getContextPath(List<ServerRouteParamDTO> predicates) {
        final String pattern = this.getPattern(predicates);
        if (CharSequenceUtil.isNotBlank(pattern)) {
            return CharSequenceUtil.replace(pattern, CommonConstant.SymbolConstant.BASE_PATH, "");
        }
        return null;
    }

    @Override
    public void flush() {
        this.sendMsg(OperateTypeEnum.QUERY);
    }

    private void getNameIsExist(String name) {
        LambdaQueryWrapper<ServerDO> queryWrapper = Wrappers.lambdaQuery(ServerDO.class)
            .eq(ServerDO::getName, name);
        boolean result = SqlHelper.retBool(super.count(queryWrapper));
        if (Boolean.TRUE.equals(result)) {
            throw new BizException(MgtCodeEnum.NAME_EXIST);
        }
    }

    private void getRouteIdIsExist(String routeId) {
        LambdaQueryWrapper<ServerDO> queryWrapper = Wrappers.lambdaQuery(ServerDO.class)
            .eq(ServerDO::getRouteId, routeId);
        boolean result = SqlHelper.retBool(super.count(queryWrapper));
        if (Boolean.TRUE.equals(result)) {
            throw new BizException(MgtCodeEnum.ROUTE_ID_EXIST);
        }
    }

    private boolean checkPredicates(List<ServerRouteParamDTO> predicates) {
        final String pattern = this.getPattern(predicates);
        if (CharSequenceUtil.isNotBlank(pattern)) {
            return SqlHelper.retBool(super.baseMapper.selectCountByPattern(pattern));
        }
        return false;
    }

    private void getPredicatesIsExist(List<ServerRouteParamDTO> predicates) {
        boolean result = this.checkPredicates(predicates);
        if (Boolean.TRUE.equals(result)) {
            throw new BizException(MgtCodeEnum.SERVER_PREDICATE_EXIST);
        }
    }

    /**
     * 查询下一个排序号.
     *
     * @return Integer
     */
    private Integer getNextSeq() {
        QueryWrapper<ServerDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("max(seq) as seq");
        Function<Object, Integer> function = val -> Integer.valueOf(val.toString());
        Integer data = super.getObj(queryWrapper, function);
        return Optional.ofNullable(data).map(x -> x + 1).orElse(1);
    }

    private String getPattern(List<ServerRouteParamDTO> predicates) {
        if (CollUtil.isNotEmpty(predicates)) {
            final Optional<String> optional = predicates.stream()
                .filter(m -> MgtConstant.ServerConstant.PATH.equalsIgnoreCase(m.getName()))
                .map(m -> m.getArgs().get(MgtConstant.ServerConstant.GENKEY_0).trim()).findFirst();
            if (optional.isPresent()) {
                return optional.get().trim();
            }
        }
        return null;
    }

    private void sendMsg(OperateTypeEnum operateType) {
        try {
            final MessageDTO messageDTO = new MessageDTO();
            messageDTO.setOperateType(operateType);
            final RTopic rTopic = this.redissonClient.getTopic(MgtConstant.TOPIC_SERVER_ROUTE);
            rTopic.publishAsync(messageDTO);
            log.info("发送redis 服务路由 topic成功={}", messageDTO);
        } catch (Exception ex) {
            log.error("redis 服务路由 topic Exception={}", ex);
        }
    }
}
